const fetch = require('nb-fetch/fetch')
const db = require('../libs/db')
const Player = db.model('player')
const User = db.model('user')
const Log = db.model('log')
const Pagination = require('../libs/pagination')
const vdjs = require('vdjs')


exports.playerList = async ctx => {
  var {page, limit, sex, freeze, keyword} = ctx.query
  var where = {}
  var include = []
  var order = []
  if (typeof freeze !== 'undefined') {
    where.freeze = ~~freeze ? 1 : 0
  }
  if (sex) {
    where.sex = ~~sex
  }
  if (keyword) {
    var kw = '%'+ keyword + '%'
    where.$or = {
      userId: {$like: kw},
      name: {$like: '%'+ Buffer.from(keyword).toString('base64') + '%'}
    }
  }
  limit = ~~limit || 10
  var count = await Player.count({where})
  var pages = new Pagination(count, limit)
  var offset = pages.sql(page).offset

  var result = await Player.findAll({where, include, order, offset, limit})
  var i = 0
  for (; i < result.length; i++) {
    result[i].name = Buffer.from(result[i].name, 'base64').toString()
  }

  ctx.body = {
    bool: true,
    msg: '',
    result,
    pages
  }
}

// 冻结用户
exports.freeze = async ctx => {
  var valid = vdjs.validate(ctx.request.body, {
    id: {required: true, not: '', msg: '用户id不能为空'},
    freeze: {required: true, not: '', msg: '操作值不能为空'}
  })
  if (valid.fails()) {
    ctx.body = {
      bool: false,
      msg: valid.first(),
      valid: valid.all(),
      result: null
    }
    return false
  }
  var oper = await ctx.user()
  var {id, freeze} = ctx.request.body
  var where = {}
  where.userId = id
  var player = await Player.findOne({where})
  if (!player) {
    ctx.body = {
      bool: false,
      msg: '用户不存在或者没权操作',
      result: null
    }
    return false
  }
  player.freeze = ~~freeze
  try {
    await player.save()
  } catch (err) {
    ctx.body = {
      bool: false,
      msg: '执行操作失败',
      err,
      result: null
    }
    return false
  }
  await Log.create({
    uid: oper.id,
    ip: ctx.ip,
    action: 'freeze',
    result: 'true',
    desctiption: (player.freeze === 1 ? '冻结用户' : '解冻用户') + ':' + player.userId
  })
  ctx.body = {
    bool: true,
    msg: '修改成功',
    result: player
  }
}


// 上分，下分
exports.changeGold = async ctx => {
  var valid = vdjs.validate(ctx.request.body, {
    id: {required: true, not: '', msg: '用户id不能为空'},
    gold: {required: true, not: '', msg: '金币不能为空'}
  })
  if (valid.fails()) {
    ctx.body = {
      bool: false,
      msg: valid.first(),
      valid: valid.all(),
      result: null
    }
    return false
  }
  var oper = await ctx.user()
  var {id, gold} = ctx.request.body
  console.log(typeof gold)
  var where = {
    userId: id
  }
  var player = await Player.findOne({where})
  var value = Number(gold)
  player.gold = Number(player.gold) + value
  try {
    await player.save()
  } catch (err) {
    ctx.body = {
      bool: false,
      msg: '操作失败',
      err
    }
    return false
  }
  var info = value > 0 
    ? `用户 ${player.userId} 上分${Math.abs(value)}，结余：${player.gold}。` 
    : `用户 ${player.userId} 下分${Math.abs(value)}，结余：${player.gold}。`
  await Log.create({
    uid: oper.id,
    ip: ctx.ip,
    action: 'gold',
    result: 'true',
    desctiption: info
  })
  var {key, sign} = makeSign()
  // 刷新配置缓存
  try {
    var url = process.env.RERFESH_PLAYER_GOLD_URL
    if (url) {
      await fetch.get(url, {
        type: 'text',
        params: {
          key,
          sign,
          userId: id
        }
      })
    }
  } catch (err) {
    log.error(err)
  }
  ctx.body = {
    bool: true,
    msg: '修改成功',
    result: player
  }
}

exports.playerInfo = async ctx => {
  var {pid} = ctx.params
  if (!pid) {
    return ctx.body = {
      bool: false,
      msg: '玩家id不能为空'
    }
  }
  var player = await Player.findOne({where: {userId: pid}})
  if (!player) {
    return ctx.body = {
      bool: false,
      msg: '玩家不存在'
    }
  }
  player.name = Buffer.from(player.name, 'base64').toString()
  return ctx.body = {
    bool: true,
    msg: '',
    result: player
  }
}
// 统计玩家信息
exports.statistic = async ctx => {
  var {code} = ctx.query
  var where = {}

  var count = await Player.count({where})
  var sexCount = await Player.count({attributes: ['sex'], where, group: ['sex']})
  var onlineCount = await Player.count({
    where: {
      onlineStatus: 1
    }
  })
  ctx.body = {
    bool: true,
    msg: '',
    result: {
      count,
      sexCount,
      onlineCount
    }
  }
}
